var Common = {
    alert: function (msg) {
        if (isNotNull(layer)) {
            layer.msg(msg);
        } else {
            alert(msg);
        }

        return this;
    },
    confirm: function (msg, success) {
        var result = confirm(msg);
        if (result)
            eval(success + "()");

        return this;
    },
    adapterStringlHandler: function (str, data) {
        for (var col in data) {
            eval("var replaceStr = /{" + col + "}/g");
            str = str.replace(replaceStr, data[col]);
        }
        return str;
    },
    generateUrl: function (href, map) {

        if (isNull(href)) {
            return false;
        }

        if (isNotNull(map)) {
            var keyValue = [];

            for (var key in map) {
                if (isNotNull(map[key])) {
                    keyValue.push(key + "=" + map[key]);
                }
            }

            return href + "?" + keyValue.join("&");
        } else {
            return href;
        }
    },
    generateAutoSubmitForm: function (options) {
        var defaults = {
            target: "_self",
            data: null,
            url: null,
            method: "post"
        };
        var opt = $.extend(defaults, options);

        if (isNull(opt.url) || isNull(opt.data)) {
            return false;
        }

        var form = '<form method="' + opt.method + '" id="autoSubmitForm" action="' + opt.url + '" target="' + opt.target + '">';

        for (var key in  opt.data) {
            if (isNotNull(opt.data[key])) {
                var input = '<input type="hidden" name="{name}" value="{value}" />';
                var inputModel = {
                    name: null,
                    value: null
                };
                inputModel.name = key;
                inputModel.value = opt.data[key];

                form += Common.adapterStringlHandler(input, inputModel);
            }

        }

        form += '</form>';

        $("body:eq(0)").append(form);
        $("#autoSubmitForm").submit();
    }
};

//填充html元素
$.fn.adapterHtmlHandler = function (data) {
    var thisHtml = $(this).html();
    return Common.adapterStringlHandler(thisHtml, data);
};

//清空form所有的值
$.fn.formEmpty = function () {
    $(this).find("input,select").val("");
    return this;
};

//ajax from提交
$.fn.formSubmit = function (options) {
    var defaults = {
        isNeedValidate: true, //是否需要验证
        startFun: null,
        url: null,
        type: "post",
        data: null, //扩展form表单提交字段
        dataType: "json",
        backFun: null
    };

    var $submitButton = $(this);
    var opt = $.extend(defaults, options);
    var $submitForm = $submitButton.recursiveParentNode("form");

    if (isNotNull(opt.startFun) && typeof opt.startFun === "function") {
        opt.startFun();
    }

    //参数通过jquery validate
    if (opt.isNeedValidate && !$submitForm.validationEngine("validate")) {
        return false;
    }

    if (isNotNull(opt.url)) {
        $.ajax({
            url: opt.url,
            type: opt.type,
            data: $.extend($submitForm.formDataTransJson(), opt.data),
            dataType: opt.dataType,
            success: function (result) {
                if (isNotNull(opt.backFun) && typeof opt.backFun === "function") {
                    opt.backFun(result);
                }
            }

        })
    } else {
        return false;
    }

    return this;
};

//将form中所有含有name的标签 值返回一个json,用来保存
$.fn.formDataTransJson = function () {
    var returnJson = {};
    $(this).find("[name]").each(function () {
        var $this = $(this);
        if (isNotNull($this.val())) {
            returnJson[$this.prop("name")] = $this.val();
        }
    });
    return returnJson;
};

//判断obj是否为空 空true 非空false
function isNull(obj) {
    return obj === undefined || obj === null || (typeof obj === "string" && obj.replace("/s+/g", "") === "");
}

function isNotNull(obj) {
    return !isNull(obj);
}

//递归返回指定的parent节点
$.fn.recursiveParentNode = function (specifyParentTagName) {

    if (isNull(specifyParentTagName) || typeof specifyParentTagName !== "string") {
        return false;
    }

    var $parent = $(this).parent(), currentParentTagName = $parent[0].tagName;

    if (isNull(currentParentTagName)) {
        return false;
    }

    if (specifyParentTagName.toLowerCase() === currentParentTagName.toLowerCase()) {
        return $parent;
    } else {
        return $parent.recursiveParentNode(specifyParentTagName);
    }
};

